package br.pucrs.prototipoonline.action;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.pucrs.prototipoonline.facade.ElementosFacade;
import br.pucrs.prototipoonline.json.ElementoJS;
import br.pucrs.prototipoonline.json.TelaJS;
import br.pucrs.prototipoonline.util.JSONUtil;
import br.pucrs.prototipoonline.vo.ElementoVO;


/**
 * 
 * @author Ricardo Luckei
 * @author Gelson Gentil
 *
 */
public class AbrirTelaAction extends POAjaxAction {

	private Logger logger = Logger.getLogger(AbrirTelaAction.class);
	
	public ActionForward executar(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entrando");
		
		String strTelaId = request.getParameter("telaId");
		String strTelaNome = request.getParameter("telaNome");
		logger.debug("Buscando elementos da tela ["+strTelaId +"] " + strTelaNome);
		
		ElementosFacade facade = (ElementosFacade) getFacade(ElementosFacade.class);
		ElementoVO vo = new ElementoVO();
		vo.setTelaId(Integer.valueOf(strTelaId));
		
		Collection<ElementoVO> colElems = facade.buscarElementos(vo);
		ElementoJS[] arrElems = new ElementoJS[colElems.size()];
		int cont=0;
		
		for(ElementoVO evo : colElems) {
			ElementoJS ejs = (ElementoJS) JSONUtil.toBean(evo.getDados(), ElementoJS.class);
			logger.debug("lido elemento ["+ejs.getType()+"]");
			arrElems[cont]=ejs;
			cont++;
		}
		
		TelaJS tjs = new TelaJS();
		tjs.setId(Integer.parseInt(strTelaId));
		tjs.setNome(strTelaNome);
		tjs.setElementos(arrElems);
		
		String json = JSONUtil.toJson(tjs);
		logger.debug("retorno: json " + json);
		
		writeOutput(json);
		
		logger.info("Saindo");
		return null;
	}
}
